package com.smart.manager.finance.repository;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import com.smart.common.entities.core.BaseSearch;
import com.smart.common.entities.core.Page;
import com.smart.manager.finance.entities.bodys.ROrderPop;
import com.smart.manager.finance.entities.enums.PayState;
import com.smart.manager.finance.entities.models.FinanceOrderPop;
import com.smart.manager.finance.entities.models.query.QFinanceOrderPop;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

/**
 * 支付中心-订单管理
 *
 * @author Administrator
 */

@Log4j2
@Service
@RequiredArgsConstructor
public class OrderPopRepository {


    public Page<FinanceOrderPop> pageList(ROrderPop.SearchBody search) {
        QFinanceOrderPop query = new QFinanceOrderPop();
        Opt.ofBlankAble(search.getAppId()).ifPresent(x -> query.appId.eq(x));
        Opt.ofBlankAble(search.getAppType()).ifPresent(x -> query.appType.eq(x));
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows()).order().id.desc();
        return new Page<FinanceOrderPop>().load(query.findPagedList());
    }


    /**
     * 根据订单编号查询订单信息是否存在
     *
     * @param orderId 订单编号
     * @return {@code FinanceOrderPop}
     */
    public FinanceOrderPop getOneByOrderId(String orderId) {
        FinanceOrderPop orderPop = new QFinanceOrderPop().orderId.eq(orderId).setMaxRows(1).findOne();
        Assert.notNull(orderPop, "订单信息不存在");
        return orderPop;
    }


    /**
     * @param agent agent数据主键
     * @param search   分页条件
     * @return {@link Page}<{@link FinanceOrderPop}>
     */
    public Page<FinanceOrderPop> myPageList(Long agent, BaseSearch search) {
        QFinanceOrderPop query = new QFinanceOrderPop();
        query.agent.id.eq(agent).payState.eq(PayState.PAID).setFirstRow(search.firstRow()).setMaxRows(search.maxRows()).order().id.desc();
        return new Page<FinanceOrderPop>().load(query.findPagedList());
    }


    /**
     * 获取订单详情
     *
     * @param agent agent数据主键
     * @param orderId  order数据主键
     * @return {@link FinanceOrderPop}
     */
    public FinanceOrderPop getPayDetail(Long agent, String orderId) {
        QFinanceOrderPop query = new QFinanceOrderPop();
        FinanceOrderPop record = query.orderId.eq(orderId).agent.id.eq(agent).setMaxRows(1).findOne();
        Assert.notNull(record, "订单信息不存在");
        return record;

    }
}
